package com.jizhi.onework.framework.shiro.service;


import com.jizhi.onework.framework.exception.UserPasswordNotMatchException;
import com.jizhi.onework.pojo.User;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 登录密码方法
 *
 * @author hzhang7
 */
@Component
public class PasswordService {

    private static final Logger logger = LoggerFactory.getLogger(PasswordService.class);

    /**
     * 验证
     *
     * @param user
     * @param password
     */
    public void validate(User user, String password) {
        if (!matches(user, password)) {
            throw new UserPasswordNotMatchException();
        }
    }

    /**
     * 密码比对
     *
     * @param user
     * @param newPassword
     * @return
     */
    public boolean matches(User user, String newPassword) {
        String password = encryptPassword(user.getPhone(), newPassword, user.getSalt());
        logger.warn("password = {}", password);
        return user.getPassword().equals(password);
    }


    /**
     * 加密密码
     *
     * @param username
     * @param password
     * @param salt
     * @return
     */
    public String encryptPassword(String username, String password, String salt) {
        String passwordStr = username + password + salt;
        logger.warn("passwordStr={}", passwordStr);
        return new Md5Hash(passwordStr).toHex();
    }

}
